import 'dart:io';
import 'dart:convert';
import 'dart:async';
import 'package:path/path.dart' as path;
import 'package:path_provider/path_provider.dart';
import 'package:get/get.dart';
import '../models/prompt_model.dart';
import 'logger_service.dart';

/// 存储服务 - Storage Service
/// 负责管理本地文件存储，支持多种格式和版本管理
class StorageService extends GetxService {
  static StorageService get to => Get.find();

  // 存储路径 - Storage Paths
  late String _appDataPath;
  late String _promptsPath;
  late String _versionsPath;
  late String _configPath;
  late String _indexPath;
  late String _backupPath;

  // 配置信息 - Configuration
  final _config = <String, dynamic>{}.obs;
  final _searchIndex = <String, List<String>>{}.obs;
  final _guestUserId = ''.obs;

  // 支持的格式 - Supported Formats
  static const supportedFormats = ['md', 'txt', 'doc', 'pdf'];
  static const maxVersionsPerPrompt = 10;
  static const maxStorageSize = 100 * 1024 * 1024; // 100MB

  @override
  Future<void> onInit() async {
    super.onInit();
    await _initializeStorage();
    await _loadConfiguration();
    await _loadSearchIndex();
    await _initializeGuestUser();
  }

  /// 初始化存储 - Initialize Storage
  Future<void> _initializeStorage() async {
    try {
      // 获取应用数据目录 - Get Application Data Directory
      // 使用平台特定的应用数据目录 - Use platform-specific app data directory
      Directory appDir;
      if (Platform.isAndroid || Platform.isIOS) {
        // Android 默认存储路径：内部存储空间/Prompt/PromptFlie
        // Android default storage path: Internal Storage/Prompt/PromptFlie
        try {
          final documentsDir = await getApplicationDocumentsDirectory();
          // 使用自定义路径结构 - Use custom path structure
          appDir = Directory(path.join(documentsDir.path, 'Prompt'));
          LoggerService.info('Android 应用文档目录: ${appDir.path}');
        } catch (e) {
          LoggerService.error('无法获取应用文档目录 - Cannot get app documents directory', error: e);
          // 尝试使用外部存储目录 - Try to use external storage directory
          try {
            final externalDir = await getExternalStorageDirectory();
            if (externalDir != null) {
              appDir = Directory(path.join(externalDir.path, 'Prompt'));
              LoggerService.info('使用外部存储目录: ${appDir.path}');
            } else {
              throw Exception('外部存储目录也不可用');
            }
          } catch (e2) {
            LoggerService.error('外部存储目录也不可用，使用临时目录 - External storage also unavailable, using temp directory', error: e2);
            final tempDir = await getTemporaryDirectory();
            appDir = Directory(path.join(tempDir.path, 'Prompt'));
          }
        }
      } else if (Platform.isWindows) {
        // Windows 默认存储路径：C:\Users\Administrator\Documents\PromptFlie
        // Windows default storage path: C:\Users\Administrator\Documents\PromptFlie
        final userProfile = Platform.environment['USERPROFILE'] ?? 'C:\\Users\\Administrator';
        final documentsPath = path.join(userProfile, 'Documents');
        appDir = Directory(path.join(documentsPath, 'PromptFlie'));
        LoggerService.info('Windows 文档目录: ${appDir.path}');
      } else {
        // 其他桌面平台使用当前目录 - Other desktop platforms use current directory
        appDir = Directory.current;
        LoggerService.info('桌面平台使用当前目录: ${appDir.path}');
      }
      _appDataPath = appDir.path;
      
      // 创建必要的目录 - Create Necessary Directories
      // 新版本存储在主目录，旧版本存储在 .old 后缀目录
      // New version stored in main directory, old version in .old suffix directory
      _promptsPath = path.join(_appDataPath, 'PromptFlie');
      _versionsPath = path.join(_appDataPath, 'PromptFlie', 'versions');
      _configPath = path.join(_appDataPath, 'PromptFlie', 'config');
      _indexPath = path.join(_appDataPath, 'PromptFlie', 'index');
      _backupPath = path.join(_appDataPath, 'PromptFlie', 'backup');

      // 确保目录存在 - Ensure Directories Exist
      await _ensureDirectoryExists(_promptsPath);
      await _ensureDirectoryExists(_versionsPath);
      await _ensureDirectoryExists(_configPath);
      await _ensureDirectoryExists(_indexPath);
      await _ensureDirectoryExists(_backupPath);
      
      // 加载配置 - Load Configuration
      await _loadConfiguration();
    } catch (e) {
      LoggerService.error('存储服务初始化失败 - Storage service initialization failed', error: e);
      rethrow;
    }
  }

  /// 确保目录存在 - Ensure Directory Exists
  Future<void> _ensureDirectoryExists(String dirPath) async {
    final dir = Directory(dirPath);
    if (!await dir.exists()) {
      await dir.create(recursive: true);
    }
  }

  /// 加载配置 - Load Configuration
  Future<void> _loadConfiguration() async {
    try {
      final configFile = File(path.join(_configPath, 'app_config.json'));
      if (await configFile.exists()) {
        final content = await configFile.readAsString();
        final config = json.decode(content) as Map<String, dynamic>;
        _config.assignAll(config);
      } else {
        // 创建默认配置 - Create Default Configuration
        _config.assignAll({
          'version': '1.0.0',
          'created_at': DateTime.now().toIso8601String(),
          'auto_backup': true,
          'max_versions': maxVersionsPerPrompt,
          'supported_formats': supportedFormats,
          'storage_limit': maxStorageSize,
          'custom_storage_path': '', // 自定义存储路径 - Custom storage path
          'backup_enabled': true, // 自动备份开关 - Auto backup switch
        });
        await _saveConfiguration();
      }
    } catch (e) {
      LoggerService.error('配置保存失败 - Configuration saving failed', error: e);
    }
  }

  /// 保存配置 - Save Configuration
  Future<void> _saveConfiguration() async {
    try {
      final configFile = File(path.join(_configPath, 'app_config.json'));
      await configFile.writeAsString(json.encode(_config));
    } catch (e) {
      LoggerService.error('配置保存失败 - Configuration saving failed', error: e);
    }
  }

  /// 加载搜索索引 - Load Search Index
  Future<void> _loadSearchIndex() async {
    try {
      final indexFile = File(path.join(_indexPath, 'search_index.json'));
      if (await indexFile.exists()) {
        final content = await indexFile.readAsString();
        final index = json.decode(content) as Map<String, dynamic>;
        _searchIndex.assignAll(index.map((key, value) => 
            MapEntry(key, List<String>.from(value))));
      }
    } catch (e) {
      LoggerService.error('搜索索引加载失败 - Search index loading failed', error: e);
    }
  }

  /// 保存搜索索引 - Save Search Index
  Future<void> _saveSearchIndex() async {
    try {
      final indexFile = File(path.join(_indexPath, 'search_index.json'));
      await indexFile.writeAsString(json.encode(_searchIndex));
    } catch (e) {
      LoggerService.error('搜索索引保存失败 - Search index saving failed', error: e);
    }
  }

  /// 初始化游客用户 - Initialize Guest User
  Future<void> _initializeGuestUser() async {
    try {
      final guestFile = File(path.join(_configPath, 'guest_user.json'));
      if (await guestFile.exists()) {
        final content = await guestFile.readAsString();
        final guestData = json.decode(content) as Map<String, dynamic>;
        _guestUserId.value = guestData['user_id'] ?? '';
      } else {
        // 创建新的游客用户ID - Create New Guest User ID
        _guestUserId.value = 'guest_${DateTime.now().millisecondsSinceEpoch}';
        await guestFile.writeAsString(json.encode({
          'user_id': _guestUserId.value,
          'created_at': DateTime.now().toIso8601String(),
        }));
      }
    } catch (e) {
      LoggerService.error('游客用户初始化失败 - Guest user initialization failed', error: e);
      _guestUserId.value = 'guest_${DateTime.now().millisecondsSinceEpoch}';
    }
  }

  /// 保存 Prompt - Save Prompt
  Future<bool> savePrompt(PromptModel prompt) async {
    try {
      // 验证数据 - Validate Data
      if (prompt.title.isEmpty || prompt.content.isEmpty) {
        LoggerService.warning('Prompt 数据无效 - Invalid prompt data');
        return false;
      }

      // 创建文件路径 - Create File Path
      final fileName = '${prompt.id}.json';
      final filePath = path.join(_promptsPath, fileName);
      final file = File(filePath);

      // 保存 JSON 数据 - Save JSON Data
      await file.writeAsString(json.encode(prompt.toJson()));

      // 保存内容文件 - Save Content File
      await _saveContentFile(prompt);

      // 更新搜索索引 - Update Search Index
      await _updateSearchIndex(prompt);

      // 创建版本记录 - Create Version Record
      await _createVersionRecord(prompt);

      LoggerService.info('Prompt 保存成功 - Prompt saved successfully: ${prompt.title}');
      return true;
    } catch (e) {
      LoggerService.error('Prompt 保存失败 - Prompt saving failed', error: e);
      return false;
    }
  }

  /// 保存内容文件 - Save Content File
  Future<void> _saveContentFile(PromptModel prompt) async {
    try {
      final contentDir = path.join(_promptsPath, 'content');
      await _ensureDirectoryExists(contentDir);

      final contentFileName = '${prompt.id}.${prompt.getFormat()}';
      final contentFilePath = path.join(contentDir, contentFileName);
      final contentFile = File(contentFilePath);

      await contentFile.writeAsString(prompt.content);
    } catch (e) {
      LoggerService.error('内容文件保存失败 - Content file saving failed', error: e);
    }
  }

  /// 加载 Prompt - Load Prompt
  Future<PromptModel?> loadPrompt(String promptId) async {
    try {
      final fileName = '$promptId.json';
      final filePath = path.join(_promptsPath, fileName);
      final file = File(filePath);

      if (!await file.exists()) {
        LoggerService.warning('Prompt 文件不存在 - Prompt file does not exist: $promptId');
        return null;
      }

      final content = await file.readAsString();
      final data = json.decode(content) as Map<String, dynamic>;
      final prompt = PromptModel.fromJson(data);

      LoggerService.info('Prompt 加载成功 - Prompt loaded successfully: ${prompt.title}');
      return prompt;
    } catch (e) {
      LoggerService.error('Prompt 加载失败 - Prompt loading failed', error: e);
      return null;
    }
  }

  /// 加载所有 Prompts - Load All Prompts
  Future<List<PromptModel>> loadAllPrompts() async {
    try {
      final promptsDir = Directory(_promptsPath);
      if (!await promptsDir.exists()) {
        return [];
      }

      final prompts = <PromptModel>[];
      await for (final entity in promptsDir.list()) {
        if (entity is File && entity.path.endsWith('.json')) {
          try {
            final content = await entity.readAsString();
            final data = json.decode(content) as Map<String, dynamic>;
            final prompt = PromptModel.fromJson(data);
            prompts.add(prompt);
          } catch (e) {
            LoggerService.warning('加载 Prompt 失败 - Failed to load prompt: ${entity.path}');
            continue;
          }
        }
      }

      LoggerService.info('加载了 ${prompts.length} 个 Prompts - Loaded ${prompts.length} prompts');
      return prompts;
    } catch (e) {
      LoggerService.error('加载所有 Prompts 失败 - Failed to load all prompts', error: e);
      return [];
    }
  }

  /// 删除 Prompt - Delete Prompt
  Future<bool> deletePrompt(String promptId) async {
    try {
      // 删除主文件 - Delete Main File
      final fileName = '$promptId.json';
      final filePath = path.join(_promptsPath, fileName);
      final file = File(filePath);

      if (await file.exists()) {
        await file.delete();
      }

      // 删除内容文件 - Delete Content Files
      await _deleteContentFiles(promptId);

      // 删除版本记录 - Delete Version Records
      await _deleteVersionRecords(promptId);

      // 更新搜索索引 - Update Search Index
      _searchIndex.remove(promptId);
      await _saveSearchIndex();

      LoggerService.info('Prompt 删除成功 - Prompt deleted successfully: $promptId');
      return true;
    } catch (e) {
      LoggerService.error('Prompt 删除失败 - Prompt deletion failed', error: e);
      return false;
    }
  }

  /// 删除内容文件 - Delete Content Files
  Future<void> _deleteContentFiles(String promptId) async {
    try {
      final contentDir = Directory(path.join(_promptsPath, 'content'));
      if (!await contentDir.exists()) return;

      await for (final entity in contentDir.list()) {
        if (entity is File && entity.path.contains(promptId)) {
          await entity.delete();
        }
      }
    } catch (e) {
      LoggerService.error('删除内容文件失败 - Failed to delete content files', error: e);
    }
  }

  /// 搜索 Prompts - Search Prompts
  Future<List<PromptModel>> searchPrompts(String query, {
    List<String>? categories,
    List<String>? tags,
    List<String>? formats,
  }) async {
    try {
      final allPrompts = await loadAllPrompts();
      
      return allPrompts.where((prompt) {
        // 文本搜索 - Text Search
        if (query.isNotEmpty && !prompt.matchesSearch(query)) {
          return false;
        }

        // 分类筛选 - Category Filter
        if (categories != null && categories.isNotEmpty && 
            !categories.contains(prompt.category)) {
          return false;
        }

        // 标签筛选 - Tags Filter
        if (tags != null && tags.isNotEmpty && 
            !prompt.containsTags(tags)) {
          return false;
        }

        // 格式筛选 - Format Filter
        if (formats != null && formats.isNotEmpty && 
            !formats.contains(prompt.getFormat())) {
          return false;
        }

        return true;
      }).toList();
    } catch (e) {
      LoggerService.error('搜索失败 - Search failed', error: e);
      return [];
    }
  }

  /// 更新搜索索引 - Update Search Index
  Future<void> _updateSearchIndex(PromptModel prompt) async {
    try {
      final keywords = <String>[];
      
      // 添加标题关键词 - Add Title Keywords
      keywords.addAll(prompt.title.toLowerCase().split(RegExp(r'\s+')));
      
      // 添加描述关键词 - Add Description Keywords
      keywords.addAll(prompt.description.toLowerCase().split(RegExp(r'\s+')));
      
      // 添加内容关键词 - Add Content Keywords
      keywords.addAll(prompt.content.toLowerCase().split(RegExp(r'\s+')));
      
      // 添加标签 - Add Tags
      keywords.addAll(prompt.tags.map((tag) => tag.toLowerCase()));
      
      // 添加分类 - Add Category
      keywords.add(prompt.category.toLowerCase());

      // 去重并过滤空值 - Remove Duplicates and Filter Empty Values
      final uniqueKeywords = keywords
          .where((keyword) => keyword.isNotEmpty && keyword.length > 1)
          .toSet()
          .toList();

      _searchIndex[prompt.id] = uniqueKeywords;
      await _saveSearchIndex();
    } catch (e) {
      LoggerService.error('搜索索引更新失败 - Search index update failed', error: e);
    }
  }

  /// 创建版本记录 - Create Version Record
  Future<void> _createVersionRecord(PromptModel prompt) async {
    try {
      final versionDir = path.join(_versionsPath, prompt.id);
      await _ensureDirectoryExists(versionDir);

      final versionData = {
        'id': prompt.id,
        'version': prompt.version,
        'title': prompt.title,
        'content': prompt.content,
        'created_at': DateTime.now().toIso8601String(),
        'content_length': prompt.getContentLength(),
        'word_count': prompt.getWordCount(),
        'template_variables': prompt.templateVariables.map((v) => v.toJson()).toList(),
      };

      final versionFileName = 'v${prompt.version}_${DateTime.now().millisecondsSinceEpoch}.json';
      final versionFilePath = path.join(versionDir, versionFileName);
      final versionFile = File(versionFilePath);

      await versionFile.writeAsString(json.encode(versionData));

      // 清理旧版本 - Clean Old Versions
      await _cleanOldVersions(prompt.id);
    } catch (e) {
      LoggerService.error('版本记录创建失败 - Version record creation failed: $e');
    }
  }

  /// 清理旧版本 - Clean Old Versions
  Future<void> _cleanOldVersions(String promptId) async {
    try {
      final versionDir = Directory(path.join(_versionsPath, promptId));
      if (!await versionDir.exists()) return;

      final versionFiles = <File>[];
      await for (final entity in versionDir.list()) {
        if (entity is File && entity.path.endsWith('.json')) {
          versionFiles.add(entity);
        }
      }

      // 按修改时间排序 - Sort by Modification Time
      versionFiles.sort((a, b) => 
          b.lastModifiedSync().compareTo(a.lastModifiedSync()));

      // 删除超出限制的版本 - Delete Versions Exceeding Limit
      if (versionFiles.length > maxVersionsPerPrompt) {
        for (int i = maxVersionsPerPrompt; i < versionFiles.length; i++) {
          await versionFiles[i].delete();
        }
      }
    } catch (e) {
      LoggerService.error('清理旧版本失败 - Failed to clean old versions: $e');
    }
  }

  /// 删除版本记录 - Delete Version Records
  Future<void> _deleteVersionRecords(String promptId) async {
    try {
      final versionDir = Directory(path.join(_versionsPath, promptId));
      if (await versionDir.exists()) {
        await versionDir.delete(recursive: true);
      }
    } catch (e) {
      LoggerService.error('删除版本记录失败 - Failed to delete version records: $e');
    }
  }

  /// 获取版本历史 - Get Version History
  Future<List<Map<String, dynamic>>> getVersionHistory(String promptId) async {
    try {
      final versionDir = Directory(path.join(_versionsPath, promptId));
      if (!await versionDir.exists()) return [];

      final versions = <Map<String, dynamic>>[];
      await for (final entity in versionDir.list()) {
        if (entity is File && entity.path.endsWith('.json')) {
          try {
            final content = await entity.readAsString();
            final versionData = json.decode(content) as Map<String, dynamic>;
            versions.add(versionData);
          } catch (e) {
            LoggerService.warning('加载版本失败 - Failed to load version: ${entity.path}');
          }
        }
      }

      // 按创建时间排序 - Sort by Creation Time
      versions.sort((a, b) => 
          DateTime.parse(b['created_at']).compareTo(DateTime.parse(a['created_at'])));

      return versions;
    } catch (e) {
      LoggerService.error('获取版本历史失败 - Failed to get version history: $e');
      return [];
    }
  }

  /// 导出 Prompt - Export Prompt
  Future<String?> exportPrompt(PromptModel prompt, String format) async {
    try {
      final exportDir = path.join(_appDataPath, 'exports');
      await _ensureDirectoryExists(exportDir);

      final fileName = '${prompt.title.replaceAll(RegExp(r'[^\w\s-]'), '').replaceAll(' ', '_')}.${format.toLowerCase()}';
      final filePath = path.join(exportDir, fileName);
      final file = File(filePath);

      String content;
      switch (format.toLowerCase()) {
        case 'md':
          content = _formatAsMarkdown(prompt);
          break;
        case 'txt':
          content = _formatAsText(prompt);
          break;
        case 'json':
          content = json.encode(prompt.toJson());
          break;
        default:
          content = prompt.content;
      }

      await file.writeAsString(content);
      LoggerService.info('Prompt 导出成功 - Prompt exported successfully: $filePath');
      return filePath;
    } catch (e) {
      LoggerService.error('Prompt 导出失败 - Prompt export failed: $e');
      return null;
    }
  }

  /// 格式化为 Markdown - Format as Markdown
  String _formatAsMarkdown(PromptModel prompt) {
    final buffer = StringBuffer();
    
    buffer.writeln('# ${prompt.title}');
    buffer.writeln();
    
    if (prompt.description.isNotEmpty) {
      buffer.writeln('## 描述');
      buffer.writeln(prompt.description);
      buffer.writeln();
    }
    
    if (prompt.tags.isNotEmpty) {
      buffer.writeln('## 标签');
      buffer.writeln(prompt.tags.map((tag) => '`$tag`').join(' '));
      buffer.writeln();
    }
    
    if (prompt.templateVariables.isNotEmpty) {
      buffer.writeln('## 模板变量');
      for (final variable in prompt.templateVariables) {
        buffer.writeln('- **${variable.name}**: ${variable.description}');
        if (variable.isRequired) {
          buffer.writeln('  - 必需参数');
        }
        if (variable.defaultValue.isNotEmpty) {
          buffer.writeln('  - 默认值: ${variable.defaultValue}');
        }
      }
      buffer.writeln();
    }
    
    buffer.writeln('## 内容');
    buffer.writeln(prompt.content);
    
    return buffer.toString();
  }

  /// 格式化为文本 - Format as Text
  String _formatAsText(PromptModel prompt) {
    final buffer = StringBuffer();
    
    buffer.writeln('标题: ${prompt.title}');
    buffer.writeln('分类: ${prompt.category}');
    buffer.writeln('格式: ${prompt.getFormat()}');
    buffer.writeln('版本: ${prompt.version}');
    buffer.writeln('创建时间: ${prompt.createdAt}');
    buffer.writeln('更新时间: ${prompt.getUpdatedAt()}');
    buffer.writeln();
    
    if (prompt.description.isNotEmpty) {
      buffer.writeln('描述:');
      buffer.writeln(prompt.description);
      buffer.writeln();
    }
    
    if (prompt.tags.isNotEmpty) {
      buffer.writeln('标签: ${prompt.tags.join(', ')}');
      buffer.writeln();
    }
    
    if (prompt.templateVariables.isNotEmpty) {
      buffer.writeln('模板变量:');
      for (final variable in prompt.templateVariables) {
        buffer.writeln('- ${variable.name}: ${variable.description}');
      }
      buffer.writeln();
    }
    
    buffer.writeln('内容:');
    buffer.writeln(prompt.content);
    
    return buffer.toString();
  }

  /// 获取存储统计 - Get Storage Statistics
  Future<Map<String, dynamic>> getStorageStatistics() async {
    try {
      final prompts = await loadAllPrompts();
      final promptsSize = await _getDirectorySize(_promptsPath);
      final versionsSize = await _getDirectorySize(_versionsPath);
      final totalSize = promptsSize + versionsSize;

      return {
        'total_prompts': prompts.length,
        'total_size': totalSize,
        'prompts_size': promptsSize,
        'versions_size': versionsSize,
        'storage_limit': maxStorageSize,
        'usage_percentage': (totalSize / maxStorageSize * 100).clamp(0, 100),
        'available_space': (maxStorageSize - totalSize).clamp(0, maxStorageSize),
        'guest_user_id': _guestUserId.value,
        'formats': prompts.map((p) => p.fileFormat).toSet().toList(),
        'categories': prompts.map((p) => p.category).toSet().toList(),
        'total_usage': prompts.fold(0, (sum, prompt) => sum + prompt.usageCount),
      };
    } catch (e) {
      LoggerService.error('获取存储统计失败 - Failed to get storage statistics: $e');
      return {};
    }
  }

  /// 获取目录大小 - Get Directory Size
  Future<int> _getDirectorySize(String dirPath) async {
    try {
      final dir = Directory(dirPath);
      if (!await dir.exists()) return 0;

      int totalSize = 0;
      await for (final entity in dir.list(recursive: true)) {
        if (entity is File) {
          totalSize += await entity.length();
        }
      }
      return totalSize;
    } catch (e) {
      LoggerService.error('获取目录大小失败 - Failed to get directory size: $e');
      return 0;
    }
  }

  /// 清理存储空间 - Clean Storage Space
  Future<void> cleanStorageSpace() async {
    try {
      // 清理旧的备份文件 - Clean Old Backup Files
      await _cleanOldBackups();

      // 清理临时文件 - Clean Temporary Files
      await _cleanTemporaryFiles();

      // 清理导出文件 - Clean Export Files
      await _cleanExportFiles();

      LoggerService.info('存储空间清理完成 - Storage space cleaning completed');
    } catch (e) {
      LoggerService.error('存储空间清理失败 - Storage space cleaning failed: $e');
    }
  }

  /// 清理旧备份 - Clean Old Backups
  Future<void> _cleanOldBackups() async {
    try {
      final backupDir = Directory(_backupPath);
      if (!await backupDir.exists()) return;

      final backupFiles = <File>[];
      await for (final entity in backupDir.list()) {
        if (entity is File) {
          backupFiles.add(entity);
        }
      }

      // 保留最新的5个备份 - Keep Latest 5 Backups
      backupFiles.sort((a, b) => 
          b.lastModifiedSync().compareTo(a.lastModifiedSync()));

      if (backupFiles.length > 5) {
        for (int i = 5; i < backupFiles.length; i++) {
          await backupFiles[i].delete();
        }
      }
    } catch (e) {
      LoggerService.error('清理旧备份失败 - Failed to clean old backups: $e');
    }
  }

  /// 清理临时文件 - Clean Temporary Files
  Future<void> _cleanTemporaryFiles() async {
    try {
      final tempDir = Directory(path.join(_appDataPath, 'temp'));
      if (await tempDir.exists()) {
        await tempDir.delete(recursive: true);
      }
    } catch (e) {
      LoggerService.error('清理临时文件失败 - Failed to clean temporary files: $e');
    }
  }

  /// 清理导出文件 - Clean Export Files
  Future<void> _cleanExportFiles() async {
    try {
      final exportDir = Directory(path.join(_appDataPath, 'exports'));
      if (!await exportDir.exists()) return;

      final now = DateTime.now();
      await for (final entity in exportDir.list()) {
        if (entity is File) {
          final lastModified = await entity.lastModified();
          final daysDiff = now.difference(lastModified).inDays;
          
          // 删除7天前的导出文件 - Delete Export Files Older Than 7 Days
          if (daysDiff > 7) {
            await entity.delete();
          }
        }
      }
    } catch (e) {
      LoggerService.error('清理导出文件失败 - Failed to clean export files: $e');
    }
  }

  /// 备份数据 - Backup Data
  Future<String?> backupData() async {
    try {
      final timestamp = DateTime.now().millisecondsSinceEpoch;
      final backupFileName = 'backup_$timestamp.json';
      final backupFilePath = path.join(_backupPath, backupFileName);

      final prompts = await loadAllPrompts();
      final backupData = {
        'version': '1.0',
        'created_at': DateTime.now().toIso8601String(),
        'guest_user_id': _guestUserId.value,
        'prompts': prompts.map((prompt) => prompt.toJson()).toList(),
        'config': _config,
        'statistics': await getStorageStatistics(),
      };

      final backupFile = File(backupFilePath);
      await backupFile.writeAsString(json.encode(backupData));

      LoggerService.info('数据备份完成 - Data backup completed: $backupFilePath');
      return backupFilePath;
    } catch (e) {
      LoggerService.error('数据备份失败 - Data backup failed: $e');
      return null;
    }
  }

  /// 恢复数据 - Restore Data
  Future<bool> restoreData(String backupFilePath) async {
    try {
      final backupFile = File(backupFilePath);
      if (!await backupFile.exists()) {
        LoggerService.warning('备份文件不存在 - Backup file does not exist');
        return false;
      }

      final content = await backupFile.readAsString();
      final backupData = json.decode(content) as Map<String, dynamic>;

      // 恢复 Prompts - Restore Prompts
      final promptsData = backupData['prompts'] as List<dynamic>;
      for (final promptData in promptsData) {
        final prompt = PromptModel.fromJson(promptData as Map<String, dynamic>);
        await savePrompt(prompt);
      }

      // 恢复配置 - Restore Configuration
      if (backupData.containsKey('config')) {
        _config.assignAll(backupData['config'] as Map<String, dynamic>);
        await _saveConfiguration();
      }

      LoggerService.info('数据恢复完成 - Data restoration completed');
      return true;
    } catch (e) {
      LoggerService.error('数据恢复失败 - Data restoration failed: $e');
      return false;
    }
  }

  // Getters 转换为方法 - Convert Getters to Methods
  String getGuestUserId() => _guestUserId.value;
  Map<String, dynamic> getConfig() => Map<String, dynamic>.from(_config);
  String getAppDataPath() => _appDataPath;
  String getPromptsPath() => _promptsPath;
  String getVersionsPath() => _versionsPath;
  
  /// 获取支持的格式 - Get Supported Formats
  List<String> getSupportedFormats() => List<String>.from(supportedFormats);
  
  /// 检查格式是否支持 - Check if Format is Supported
  bool isFormatSupported(String format) => supportedFormats.contains(format.toLowerCase());
  
  /// 获取最大版本数 - Get Max Versions
  int getMaxVersions() => maxVersionsPerPrompt;
  
  /// 获取存储限制 - Get Storage Limit
  int getStorageLimit() => maxStorageSize;
  
  /// 设置自定义存储路径 - Set Custom Storage Path
  Future<bool> setCustomStoragePath(String customPath) async {
    try {
      // 验证路径是否有效 - Validate if path is valid
      final dir = Directory(customPath);
      if (!await dir.exists()) {
        await dir.create(recursive: true);
      }
      
      // 更新配置 - Update configuration
      _config['custom_storage_path'] = customPath;
      await _saveConfiguration();
      
      // 重新初始化存储路径 - Reinitialize storage paths
      await _initializeCustomStoragePaths(customPath);
      
      LoggerService.info('自定义存储路径设置成功 - Custom storage path set successfully: $customPath');
      return true;
    } catch (e) {
      LoggerService.error('设置自定义存储路径失败 - Failed to set custom storage path: $e');
      return false;
    }
  }
  
  /// 获取自定义存储路径 - Get Custom Storage Path
  String getCustomStoragePath() => _config['custom_storage_path'] ?? '';
  
  /// 初始化自定义存储路径 - Initialize Custom Storage Paths
  Future<void> _initializeCustomStoragePaths(String customPath) async {
    try {
      _appDataPath = customPath;
      _promptsPath = path.join(_appDataPath, 'PromptFlie');
      _versionsPath = path.join(_appDataPath, 'PromptFlie', 'versions');
      _configPath = path.join(_appDataPath, 'PromptFlie', 'config');
      _indexPath = path.join(_appDataPath, 'PromptFlie', 'index');
      _backupPath = path.join(_appDataPath, 'PromptFlie', 'backup');
      
      // 确保目录存在 - Ensure directories exist
      await _ensureDirectoryExists(_promptsPath);
      await _ensureDirectoryExists(_versionsPath);
      await _ensureDirectoryExists(_configPath);
      await _ensureDirectoryExists(_indexPath);
      await _ensureDirectoryExists(_backupPath);
    } catch (e) {
      LoggerService.error('初始化自定义存储路径失败 - Failed to initialize custom storage paths: $e');
    }
  }
  
  /// 迁移旧版本数据 - Migrate Old Version Data
  Future<bool> migrateOldVersionData() async {
    try {
      String oldDataPath;
      
      // 根据平台确定旧版本数据路径 - Determine old version data path based on platform
      if (Platform.isAndroid || Platform.isIOS) {
        final documentsDir = await getApplicationDocumentsDirectory();
        if (Platform.isAndroid) {
          final externalDir = await getExternalStorageDirectory();
          oldDataPath = path.join(externalDir?.path ?? documentsDir.path, 'Prompt', 'PromptFlie.old');
        } else {
          oldDataPath = path.join(documentsDir.path, 'Prompt', 'PromptFlie.old');
        }
      } else if (Platform.isWindows) {
        final userProfile = Platform.environment['USERPROFILE'] ?? '';
        oldDataPath = path.join(userProfile, 'Documents', 'PromptFlie.old');
      } else {
        oldDataPath = path.join(Directory.current.path, 'PromptFlie.old');
      }
      
      final oldDir = Directory(oldDataPath);
      if (!await oldDir.exists()) {
        LoggerService.info('未找到旧版本数据 - No old version data found');
        return true;
      }
      
      // 迁移数据 - Migrate data
      await _copyDirectory(oldDir, Directory(_promptsPath));
      
      // 重命名旧目录为备份 - Rename old directory as backup
      final backupOldPath = '${oldDataPath}_backup_${DateTime.now().millisecondsSinceEpoch}';
      await oldDir.rename(backupOldPath);
      
      LoggerService.info('旧版本数据迁移完成 - Old version data migration completed');
      return true;
    } catch (e) {
      LoggerService.error('旧版本数据迁移失败 - Old version data migration failed: $e');
      return false;
    }
  }
  
  /// 复制目录 - Copy Directory
  Future<void> _copyDirectory(Directory source, Directory destination) async {
    try {
      if (!await destination.exists()) {
        await destination.create(recursive: true);
      }
      
      await for (final entity in source.list(recursive: false)) {
        if (entity is Directory) {
          final newDirectory = Directory(path.join(destination.path, path.basename(entity.path)));
          await _copyDirectory(entity, newDirectory);
        } else if (entity is File) {
          final newFile = File(path.join(destination.path, path.basename(entity.path)));
          await entity.copy(newFile.path);
        }
      }
    } catch (e) {
      LoggerService.error('复制目录失败 - Failed to copy directory: $e');
    }
  }
  
  /// 启用/禁用自动备份 - Enable/Disable Auto Backup
  Future<void> setAutoBackupEnabled(bool enabled) async {
    try {
      _config['backup_enabled'] = enabled;
      await _saveConfiguration();
      LoggerService.info('自动备份设置更新 - Auto backup setting updated: $enabled');
    } catch (e) {
      LoggerService.error('更新自动备份设置失败 - Failed to update auto backup setting: $e');
    }
  }
  
  /// 检查是否启用自动备份 - Check if Auto Backup is Enabled
  bool isAutoBackupEnabled() => _config['backup_enabled'] ?? true;
  
  /// 自动备份新文件 - Auto Backup New File
  Future<void> autoBackupNewFile(PromptModel prompt) async {
    try {
      if (!isAutoBackupEnabled()) return;
      
      final timestamp = DateTime.now().millisecondsSinceEpoch;
      final backupFileName = 'auto_backup_${prompt.id}_$timestamp.json';
      final backupFilePath = path.join(_backupPath, backupFileName);
      
      final backupData = {
        'type': 'auto_backup',
        'created_at': DateTime.now().toIso8601String(),
        'prompt': prompt.toJson(),
      };
      
      final backupFile = File(backupFilePath);
      await backupFile.writeAsString(json.encode(backupData));
      
      LoggerService.info('新文件自动备份完成 - New file auto backup completed: ${prompt.title}');
    } catch (e) {
      LoggerService.error('新文件自动备份失败 - New file auto backup failed: $e');
    }
  }
}